// @ts-nocheck==
import * as util from "@/utils"
import * as XLSX from 'xlsx'
import * as em from '@/enums';

export default function (cfg: cfg = {}) {
    const { 单项组, 插组件 } = cfg

    const 导出excel = () => {
        // let arr = util.数组过滤一排除(单项组, '名称', ['CreatedAt', 'UpdatedAt', 'DeletedAt', '创建者', '更新者', '删除者'])
        // console.log(`arr 👉`, arr)
        let arr = []
        for (const 单项 of 单项组!) {
            let obj = util.成对象_排除属性(单项, ['CreatedAt', 'UpdatedAt', 'DeletedAt', '创建者', '更新者', '删除者'])
            arr.push(obj)
        }
        console.log(`arr 👉`, arr)

        const ws = XLSX.utils.json_to_sheet(arr)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        let 文件名 = 插组件?.组件.名称
        XLSX.writeFile(wb, 文件名 + '.xlsx')
    }

    const 导入excel = (file: any) => {
        const reader = new FileReader()
        reader.onload = (e: ProgressEvent<FileReader>) => {
            const data = new Uint8Array(e.target?.result as ArrayBuffer)
            const workbook = XLSX.read(data, { type: 'array' })
            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]
            const newData = XLSX.utils.sheet_to_json(worksheet) as any[]
            // console.log(`newData 👉`, newData)
            // 插组件?.组件.字段组
            // util.数组重予(单项组, newData)
            if (newData) {
                for (const 单项 of newData) {
                    Object.entries(单项).forEach(([key, value]) => {
                        // console.log(`键：${key}，值：${value}`);
                        let 字段 = 插组件?.取字段(key)
                        console.log(`字段 👉`, 字段)
                        switch (字段?.类型) {
                            case em.字段类型.人民币:
                                // -2表示保留到元👇
                                单项[key] = util.元转分(value, -2)
                                console.log(`单项[key] 👉`, 单项[key])
                                break;
                        }
                    });
                }
            }
            util.数组重予(单项组, newData)
            // console.log(`单项组 👉`,单项组)
        }
        reader.readAsArrayBuffer(file.raw)
    }
    return {
        导出excel,
        导入excel,
    }
}
